<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<title>phonegap_device_network_notification01</title>
<link href="../jquery.mobile-1.3.2.css" rel="stylesheet" type="text/css"/>
<script src="../jquery.js" type="text/javascript"></script>
<script src="../jquery.mobile-1.3.2.js" type="text/javascript"></script>
<script src="../cordova.js" type="text/javascript"></script>
<style type="text/css">
	#ball {
    position: absolute;
    z-index: 0;
    left: 20px;
    top: 100px;
    background: #f00;
}
</style>
<script type="text/javascript" charset="utf-8">
    var watchID = null;
    document.addEventListener("deviceready", onDeviceReady, false);

	function drawCircle(x,y) {
	    var ctx = document.getElementById("ball").getContext('2d');
	    var rd = 10;
	    ctx.beginPath();
	    ctx.arc(x, y, rd, 0, Math.PI * 2, false);
	    ctx.closePath();
	    ctx.fillStyle = "yellow";
	    ctx.fill();
	}
	
	function clear() {
	    var ctx = document.getElementById("ball").getContext('2d');
	    ctx.clearRect(0,0,200,200);
	}

    function onDeviceReady() {
    	drawCircle(10,10);
        startWatch();
    }


    function startWatch() {
        var options = { frequency: 40 };

        watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
    }

    function stopWatch() {
        if (watchID) {
            navigator.accelerometer.clearWatch(watchID);
            watchID = null;
        }
    }

	var oldX = 10, oldY = 10;
    // 获取加速度信息成功后的回调函数
    function onSuccess(newValue) {
	    if(10<=oldX<180&&10<=oldY<180){
			clear();
			drawCircle(oldX,oldY);
		}
		oldX -= newValue.x;
		oldY += newValue.y;
        var element = document.getElementById('accelerometer');
        element.innerHTML = 'X: ' + oldX + '<br />' +
                            'Y: ' + oldY + '<br />';
    }

    // 获取加速度信息失败后的回调函数
    function onError() {
        alert('onError!');
    }

</script>
</head> 
<body>
<div data-role="page">
		<div data-role="header">
			<h1>PhoneGap100实战</h1>
		</div>
		<div data-role="content">
			<div id="accelerometer">开启重力感应...</div>
		    <button onclick="stopWatch();">停止重力感应</button>
		    <!--<canvas id="ball" width="200" height="200"></canvas>	-->
		</div>		
		<div data-role="footer">
			<h4>&nbsp;</h4>
		</div>
</div>

</body>
</html>
